package com.cyys.modules.system.service.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyys.common.ql.AR;
import com.cyys.common.services.CyysBaseService;
import com.cyys.common.utils.StringUtil;
import com.cyys.modules.core.model.TreeBuilder;
import com.cyys.modules.system.dao.user.MenuDao;
import com.cyys.modules.system.dao.user.MenuRoleDao;
import com.cyys.modules.system.model.user.Menu;
import com.cyys.modules.system.model.user.MenuRole;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service("menuService")
@Transactional(readOnly = true)
public class MenuService extends CyysBaseService<MenuDao, Menu> {

	@Resource
	private MenuRoleDao menuRoleDao;

	@Transactional(readOnly = false)
	public AR save(Menu menu)  {
		if (StringUtil.isEmpty(menu.getParentId()) || menu.getParentId().equals("0")) { // 保存根节点
			menu.setParentId("0");
		} else {
			Menu parentMenu = dao.selectById(menu.getParentId());
			// 修改父类的属性
			parentMenu.setHasChild(1); // 设置有子类
			dao.updateById(parentMenu);
		}
		menu.setHasChild(0);
		dao.insert(menu);
		return AR.ok(menu,"菜单保存成功");
	}

	@Transactional(readOnly = false)
	public AR deleteById(String id)  {
		Menu menu = dao.selectById(id);
		int count = dao.chlidNum(id);
		if (count > 0) {
			return AR.failed("有子元素，不允许删除");
		}
		dao.deleteById(id);//和下面代码位置不能变
		// 修改父类属性
		if (StringUtil.isNotEmpty(menu.getParentId())) {
			Menu parentMenu = dao.selectById(menu.getParentId());
			int parentCount = dao.chlidNum(menu.getParentId());
			if (parentCount == 0) {
				parentMenu.setHasChild(0);
				dao.updateById(parentMenu);
			}
		}
		return AR.ok("菜单删除成功");
	}

	@Transactional(readOnly = false)
	public AR deleteByIds(String ids)  {
		String[] idsArr = ids.split(",");
		// 检查批量删除数据是否存在问题
		List<Menu> menuList = dao.listByIds(idsArr);

		for (Menu menu : menuList) {
			int count = dao.chlidNum(menu.getId());
			if (count > 0) {
				return AR.failed(menu.getName() + "有子元素，不允许删除");
			}
		}
		dao.deleteBatchIds(Arrays.asList(idsArr));//和下面代码位置不能变
		for (Menu menu : menuList) {
			// 修改父类属性
			if (StringUtil.isNotEmpty(menu.getParentId())) {
				Menu parentMenu = dao.selectById(menu.getParentId());
				int parentCount = dao.chlidNum(menu.getParentId());
				if (parentCount == 0) {
					parentMenu.setHasChild(0);
					dao.updateById(parentMenu);
				}
			}
		}
		return AR.ok("菜单删除成功");
	}

	/**
	 *
	 * @param parentId
	 * @param isDeveloper 是否开发者
	 * @param isFirst
	 * @return
	 * @
	 */
	public List<Menu> listByParentId(String parentId, boolean isDeveloper, boolean isFirst)  {
		if (StringUtil.isEmpty(parentId)) {
			List<Menu> list = dao.getByParentId(null, isDeveloper);
			List<Menu> returnList = getChlid(list, isDeveloper, isFirst);
			return returnList;
		} else {
			return dao.getByParentId(parentId, isDeveloper);
		}
	}

	private List<Menu> getChlid(List<Menu> list, boolean isDeveloper, boolean isFirst)  {
		List<Menu> returnList = new ArrayList<Menu>();
		for (Menu menu : list) {
			List<Menu> childrenList = dao.getByParentId(menu.getId(), isDeveloper);
			if (childrenList != null && childrenList.size() > 0) {
				menu.setChildren(childrenList);
				getChlid(childrenList, isFirst, isDeveloper);
			}
			returnList.add(menu);
		}
		return returnList;
	}

	/**
	 * 设置角色菜单
	 *
	 * @param roleId
	 * @param menuIds
	 *            菜单id字符串，号隔开
	 * @return
	 * @
	 */
	@Transactional(readOnly = false)
	public void setMenuRole(String roleId, String menuIds)  {
		// 删除原有菜单权限
		menuRoleDao.deleteByRoleId(roleId);
		// 添加新的菜单权限
		if (menuIds != null && !menuIds.equals("")) {
			List<MenuRole> list = Lists.newArrayList();
			String[] menuIdsInt = menuIds.split(",");
			for (int i = 0; i < menuIdsInt.length; i++) {
				MenuRole menuRole = new MenuRole();
				menuRole.setRoleId(roleId);
				menuRole.setMenuId(menuIdsInt[i]);
				menuRoleDao.insert(menuRole);
			}
		}
	}

	public Set<String> shiroByRoleIds(String[] roleIds)  {
		return dao.shiroByRoleIds(roleIds);
	}

	/**
	 * 获取角色权限菜单
	 *
	 * @param roleId
	 */
	public List<Menu> getMenuByRoleId(String roleId){
		return dao.getMenuByRoleId(roleId);
	}

	/**
	 * 根据菜单名和权限获取是否有菜单
	 *
	 */
	public Menu getByNameAndShiro(String name,String shiro){
		Menu entity = new Menu();
		entity.setShiro(shiro);
		entity.setName(name);
		QueryWrapper<Menu> qw = new QueryWrapper<>();
		qw.setEntity(entity);
		return dao.selectOne(qw);
	}

	public List<Menu> listAllTree(QueryWrapper<Menu> qw) {
		return TreeBuilder.buildByRecursive(dao.selectList(qw));
	}
}
